package com.itlong.cloud.miniprogram;

import com.itlong.cloud.POJO.DTO.smartcard.SmartCardQRCodeContentDTO;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.noncore.miniprogram.IMiniProgramPushMessageServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.Set;

/**
 * <desc>
 *      小程序定时推送访客二维码内容
 * </desc>
 *
 * @createDate 2021/6/4
 **/
@EnableScheduling // 启用定时任务
@RestController
public class MiniProgramVisitorContentPushTimeTask {

    @Autowired
    IMiniProgramPushMessageServiceClient iMiniProgramPushMessageServiceClient;

    @Autowired
    RedisService redisService;
    /**
     * <desc>
     *      定时推送给小程序访客内容
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/6/4
     */
    @Scheduled(cron = "0 * * * * ?")
    public void timeTaskPushVisitorContent(){
        try {

            Set<String> keysSet = redisService.getKeys(RedisConstant.SMARTCARD_VISITOR_QR_CODE_CONTENT_CACHE_KEY);
            for (String key : keysSet){
                SmartCardQRCodeContentDTO smartCardQRCodeContentDTO = (SmartCardQRCodeContentDTO) redisService.getObject(key, SmartCardQRCodeContentDTO.class);

                if (smartCardQRCodeContentDTO == null){
                    continue;
                }

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(DateUtil.formatStringToDate(smartCardQRCodeContentDTO.getUpdateTime(),DateUtil.FULLYYYYMMDDHHMMSS));
                calendar.add(Calendar.SECOND, 30);// 加30s
                Date beforeD = calendar.getTime();
                if (beforeD.after(new Date())){
                    //30s内二维码有变更过，此次不再推送变更消息
                    continue;
                }
                smartCardQRCodeContentDTO.getUpdateTime();

                String visitorId = key.replace(RedisConstant.SMARTCARD_VISITOR_QR_CODE_CONTENT_CACHE_KEY, "");
                iMiniProgramPushMessageServiceClient.pushMessage(visitorId);
            }

        } catch (Exception e) {
            throw new DataAccessException("【定时推送小程序二维码内容】定时推送小程序二维码内容失败", e);
        }
    }
}
